package com.tanjun.gateway.gatewayservice.controller.admin;

import cn.dev33.satoken.reactor.context.SaReactorSyncHolder;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.tanjun.common.model.R;
import com.tanjun.gateway.gatewayservice.biz.UserLoginBiz;
import com.tanjun.gateway.gatewayservice.config.StpUtilKit;
import com.tanjun.gateway.gatewayservice.request.AdminUserLoginRequest;
import com.tanjun.gateway.gatewayservice.response.CaptchaResponse;
import com.tanjun.gateway.gatewayservice.response.LoginResponse;
import com.tanjun.gateway.gatewayservice.response.UserInfoResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.tanjun.common.constants.UrlConstant.URL_AUTH.AUTH;
import static com.tanjun.common.constants.UrlConstant.URL_AUTH.OPEN;
import static com.tanjun.common.constants.UrlConstant.URL_MODULE.GATEWAY_SERVICE;
import static com.tanjun.common.constants.UrlConstant.URL_USER.ADMIN;

@Slf4j
@RestController
@RequestMapping(GATEWAY_SERVICE+ADMIN+"/user")
public class LoginController {

    @Resource
    private UserLoginBiz userLoginBiz;


    @PostMapping(OPEN+"/login")
    public Mono<R<LoginResponse>> login(@RequestBody @Validated AdminUserLoginRequest paramVo, ServerWebExchange exchange){
        try {
            SaReactorSyncHolder.setContext(exchange);
            System.out.println("是否登录：" + StpUtil.isLogin());
            userLoginBiz.loginByUserName(paramVo);
            SaTokenInfo saTokenInfo= StpUtilKit.adminStpLogic.getTokenInfo();
            LoginResponse response=LoginResponse.builder().
                    token(saTokenInfo.getTokenValue())
                    .expires(saTokenInfo.getTokenTimeout())
                    .build();
            return Mono.just(R.OK(response));
        } finally {
            SaReactorSyncHolder.clearContext();
        }
    }

    @GetMapping(OPEN+"/getCaptcha")
    public Mono<R<CaptchaResponse>> getCaptcha(){
        return Mono.just(R.OK(userLoginBiz.getCaptcha()));
    }


    /**
     * 获取当前登录用户信息
     * @return
     */
    @GetMapping(AUTH+"/me")
    public Mono<R<UserInfoResponse>> me(ServerWebExchange exchange){
        SaReactorSyncHolder.setContext(exchange);
       return Mono.just(R.OK(userLoginBiz.getLoginUserInfo()));
    }

    /**
     * 退出登录
     * @return 退出登录
     */
    @GetMapping(OPEN+"/logout")
    public Mono<R> logout(){
        userLoginBiz.logout();
        return Mono.just(R.OK());
    }




}
